package com.adk.backend.service.impl;

import com.adk.backend.common.PageResult;
import com.adk.backend.entity.LxAdmin;
import com.adk.backend.mapper.AdminMapper;
import com.adk.backend.service.AdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;

/**
 * 管理员服务实现类
 */
@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, LxAdmin> implements AdminService {
    
    @Value("${jwt.password-key:bm}")
    private String passwordKey;
    
    @Override
    public PageResult<LxAdmin> getAdminList(Map<String, Object> params) {
        Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) params.getOrDefault("pageSize", 20);
        Integer gid = (Integer) params.get("gid");
        Integer cid = (Integer) params.get("cid");
        Integer status = (Integer) params.get("status");
        
        Page<LxAdmin> page = new Page<>(pageNum, pageSize);
        QueryWrapper<LxAdmin> wrapper = new QueryWrapper<>();
        
        // 用户组筛选
        if (gid != null && gid > 0) {
            wrapper.eq("user_type", gid);
            // 如果是客户用户（user_type=13），需要关联客户表
            if (gid == 13 && cid != null && cid > 0) {
                wrapper.eq("customer_id", cid);
            }
        } else {
            // 默认不显示客户用户
            wrapper.ne("user_type", 13);
        }
        
        // 客户筛选（仅当gid=13时生效）
        if (cid != null && cid > 0 && gid != null && gid == 13) {
            wrapper.eq("customer_id", cid);
        }
        
        // 状态筛选（PHP中status=1表示正常，status=2表示已禁用，但数据库status=0表示正常，status=1表示禁用）
        if (status != null && status > 0) {
            wrapper.eq("status", status - 1);
        }
        
        // 按添加时间倒序
        wrapper.orderByDesc("add_time");
        
        Page<LxAdmin> result = this.page(page, wrapper);
        return PageResult.of(result.getTotal(), result.getRecords(), pageNum, pageSize);
    }
    
    @Override
    public LxAdmin createAdmin(LxAdmin admin, String password) {
        if (!StringUtils.hasText(password)) {
            throw new IllegalArgumentException("密码不能为空");
        }
        
        // 检查邮箱是否已存在
        QueryWrapper<LxAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("email", admin.getEmail());
        LxAdmin exist = this.getOne(wrapper);
        if (exist != null) {
            throw new IllegalArgumentException("邮箱已存在");
        }
        
        // 加密密码
        admin.setAdminpwd(md5(passwordKey + password));
        admin.setAddTime((int) (System.currentTimeMillis() / 1000));
        
        this.save(admin);
        return admin;
    }
    
    @Override
    public boolean updateAdmin(LxAdmin admin, String password) {
        // 检查邮箱是否已被其他用户使用
        if (StringUtils.hasText(admin.getEmail())) {
            QueryWrapper<LxAdmin> wrapper = new QueryWrapper<>();
            wrapper.eq("email", admin.getEmail());
            wrapper.ne("id", admin.getId());
            LxAdmin exist = this.getOne(wrapper);
            if (exist != null) {
                throw new IllegalArgumentException("邮箱已存在");
            }
        }
        
        // 如果提供了新密码，则更新密码
        if (StringUtils.hasText(password)) {
            LxAdmin oldAdmin = this.getById(admin.getId());
            if (oldAdmin != null && !oldAdmin.getAdminpwd().equals(password)) {
                admin.setAdminpwd(md5(passwordKey + password));
            }
        }
        
        return this.updateById(admin);
    }
    
    @Override
    public boolean deleteAdmin(Long id) {
        // 不能删除id=11的用户
        if (id != null && id == 11) {
            throw new IllegalArgumentException("不能删除该用户");
        }
        return this.removeById(id);
    }
    
    @Override
    public boolean toggleStatus(Long id) {
        LxAdmin admin = this.getById(id);
        if (admin == null) {
            return false;
        }
        
        // 切换状态：0-正常，1-禁用
        if (admin.getStatus() == null || admin.getStatus() == 0) {
            admin.setStatus(1);
        } else {
            admin.setStatus(0);
        }
        
        return this.updateById(admin);
    }
    
    @Override
    public boolean logout(Long id) {
        LxAdmin admin = this.getById(id);
        if (admin == null) {
            return false;
        }
        
        // 清除Token
        admin.setToken("");
        return this.updateById(admin);
    }
    
    /**
     * MD5加密
     */
    private String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }
    
    @Override
    public boolean updateUserTypeToDefault(Integer userType) {
        QueryWrapper<LxAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("user_type", userType);
        
        LxAdmin updateAdmin = new LxAdmin();
        updateAdmin.setUserType(2);
        updateAdmin.setStatus(1); // 禁用
        
        return this.update(updateAdmin, wrapper);
    }
    
    @Override
    public java.util.List<java.util.Map<String, Object>> getSalesUsersWithCs() {
        // 查询业务员（user_type in (4, 6, 35)）
        QueryWrapper<LxAdmin> wrapper = new QueryWrapper<>();
        wrapper.in("user_type", 4, 6, 35);
        wrapper.orderByAsc("username");
        
        java.util.List<LxAdmin> salesUsers = this.list(wrapper);
        java.util.List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
        
        for (LxAdmin user : salesUsers) {
            java.util.Map<String, Object> userMap = new java.util.HashMap<>();
            userMap.put("id", user.getId());
            userMap.put("username", user.getUsername());
            userMap.put("email", user.getEmail());
            userMap.put("csId", user.getCsId());
            
            // 如果有关联的客服，查询客服信息
            if (user.getCsId() != null && !user.getCsId().isEmpty()) {
                java.util.List<String> csUsernames = new java.util.ArrayList<>();
                String[] csIds = user.getCsId().split(",");
                for (String csIdStr : csIds) {
                    if (csIdStr.trim().isEmpty()) continue;
                    try {
                        Long csId = Long.parseLong(csIdStr.trim());
                        LxAdmin cs = this.getById(csId);
                        if (cs != null) {
                            csUsernames.add(cs.getUsername() + "(" + cs.getEmail() + ")");
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效的ID
                    }
                }
                userMap.put("csUsername", String.join("<br />", csUsernames));
            } else {
                userMap.put("csUsername", "");
            }
            
            result.add(userMap);
        }
        
        return result;
    }
    
    @Override
    public java.util.Map<String, Object> getSalesUserDetail(Long id) {
        LxAdmin user = this.getById(id);
        if (user == null) {
            return null;
        }
        
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("id", user.getId());
        result.put("username", user.getUsername());
        result.put("email", user.getEmail());
        result.put("csId", user.getCsId());
        result.put("csRemarks", user.getCsRemarks());
        
        // 如果有关联的客服，查询客服详情
        if (user.getCsId() != null && !user.getCsId().isEmpty()) {
            java.util.List<Long> csIds = new java.util.ArrayList<>();
            String[] csIdArray = user.getCsId().split(",");
            for (String csIdStr : csIdArray) {
                if (csIdStr.trim().isEmpty()) continue;
                try {
                    csIds.add(Long.parseLong(csIdStr.trim()));
                } catch (NumberFormatException e) {
                    // 忽略无效的ID
                }
            }
            result.put("csIds", csIds);
        } else {
            result.put("csIds", new java.util.ArrayList<>());
        }
        
        return result;
    }
    
    @Override
    public boolean updateSalesUserCs(Long id, java.util.List<Long> csIds) {
        LxAdmin admin = this.getById(id);
        if (admin == null) {
            return false;
        }
        
        // 将csIds列表转换为逗号分隔的字符串
        if (csIds != null && !csIds.isEmpty()) {
            String csIdStr = csIds.stream()
                    .map(String::valueOf)
                    .collect(java.util.stream.Collectors.joining(","));
            admin.setCsId(csIdStr);
        } else {
            admin.setCsId("");
        }
        
        return this.updateById(admin);
    }
    
    @Override
    public java.util.List<LxAdmin> getCsUsers() {
        QueryWrapper<LxAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("user_type", 42);
        wrapper.orderByAsc("username");
        return this.list(wrapper);
    }
}

